package com.example.layui_project.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.layui_project.comm.action.BaseController;
import com.example.layui_project.dto.GridParams;
import com.example.layui_project.dto.JsonData;
import com.example.layui_project.dto.TableParams;
import com.example.layui_project.dto.TableResult;
import com.example.layui_project.entity.Supplier;
import com.example.layui_project.entity.SysUser;
import com.example.layui_project.enums.ResultCode;
import com.example.layui_project.service.SupplierService;
import com.example.layui_project.service.UserService;
import com.example.layui_project.utils.BestUitls;
import com.example.layui_project.utils.EasyExcelUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.*;

@Controller
@RequestMapping("supplier")
public class SupplierController extends BaseController {
    @Autowired
    private SupplierService supplierService;

    @GetMapping("toSupplierList.do")
    public String toSupplierList(){
        boolean permission = super.checkPermission();
        if (!permission){
            // 说明权限校验未通过返回
            return "error";
        }
        return "basic/supplierList";
    }

    @RequestMapping("findData.do")
    @ResponseBody
    public TableResult findData(int page, int limit,String name){
        TableParams tableParams = new TableParams();
        HashMap<String, Object> ps = new HashMap<>();
        ps.put("name",name);
        tableParams.setPs(ps);
        tableParams.setPageNum(page-1);
        tableParams.setPageSize(limit);
        TableResult<Supplier> tableResult = supplierService.find(tableParams);
        tableResult.setCode(0);
        return tableResult;
    }

    @PostMapping("add.do")
    @ResponseBody
    public JsonData add(@RequestBody Supplier supplier){
        try {
            boolean add = supplierService.add(supplier);
            if(add){
                return JsonData.success();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
    }

    @PostMapping("del.do")
    @ResponseBody
    public JsonData del(Integer id){
        try {
            boolean del = supplierService.del(id);
            if(del){
                return JsonData.success();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
    }

    @PostMapping("update.do")
    @ResponseBody
    public JsonData update(@RequestBody Supplier supplier){
        try {
            boolean update = supplierService.update(supplier);
            if(update){
                return JsonData.success();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
    }
    @PostMapping("batchdel.do")
    @ResponseBody
    public boolean batchdel(@RequestBody List<Long> ids) {

        return supplierService.batchDel(ids);
    }
    @PostMapping("export.do")
    @ResponseBody
    public JsonData exportData(){
        try {
            List<Supplier> suppliers = supplierService.selectAll();
            if(BestUitls.isNotBlank(suppliers)){
                System.out.printf(JSONObject.toJSONString(suppliers));
                return JsonData.success(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getInfo(), JSONObject.toJSONString(suppliers));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
    }

    // 导入
    @PostMapping("upload.do")
    @ResponseBody
    public JsonData upload(HttpServletRequest request) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
            /** 页面控件的文件流* */
            MultipartFile multipartFile = null;
            Map<String, MultipartFile> map = multipartRequest.getFileMap();
            for (Iterator<String> i = map.keySet().iterator(); i.hasNext();) {
                Object obj = i.next();
                multipartFile = map.get(obj);
            }
            FileInputStream fis = (FileInputStream)multipartFile.getInputStream();
            if (fis == null) {
                return JsonData.fail(-1,"上传文件不能为空");
            } else {
                boolean isOk = supplierService.importData(fis);
                if (isOk){
                    return JsonData.success(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getInfo());
                }else {
                    return  JsonData.fail(-1,"导入失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
    }

    @PostMapping("exportData.do")
    public void exportData(@RequestParam String data, @RequestParam String headInfo, HttpServletResponse response) {
        try {
            String fileName = "供应商.xlsx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            // 该参数是一个json字符串 进行解析
            // GridParams gridParams = new GridParams();
            ObjectMapper mapper = new ObjectMapper();
//            GridParams gridParams = mapper.readValue(data, GridParams.class);
            TableParams tableParams = mapper.readValue(data, TableParams.class);
            // 查询出需要导出的数据
            List<Supplier> infos = supplierService.find(tableParams).getData();
            // 表头信息要根据查询条件来动态
            List<List<String>> rows = new ArrayList<List<String>>();
            String[] split = headInfo.split(",");
            List<String> asList = Arrays.asList(split);
            List<String> head = new ArrayList<>(asList);
            head.remove("序列");
            for (Supplier info : infos) {
                List<String> row = getRow(head, info);
                rows.add(row);
            }
            ServletOutputStream ops = response.getOutputStream();
            EasyExcelUtil.writeExcelWithOutModel(ops, head, rows, "供应商");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public List<String> getRow(List<String> head, Supplier info) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        List<String> row = new ArrayList<>();
        for (String h : head) {
            switch (h) {
                case "供应商名称":
                    row.add(info.getName());
                    break;
                case "供应商电话":
                    row.add(info.getPhone());
                    break;
                case "地址":
                    row.add(info.getAddress());
                    break;
                case "邮箱":
                    row.add(info.getEmail());
                    break;
                case "供应商类型":
                    row.add(info.getType());
                    break;
                default:
                    break;
            }
        }
        return row;
    }

}
